package controllers

import (
	"github.com/astaxie/beego"
	"gopkg.in/mgo.v2"
	"github.com/astaxie/beego/logs"
	"strconv"
	"steam_api/models"
	"encoding/json"
	"strings"
)



var co_log *logs.BeeLogger
func init()  {
	co_log=logs.NewLogger()
	//设置异步输出日志提升性能
	co_log=co_log.Async()
	//设置输出文件名和行号
	co_log.EnableFuncCallDepth(true)
	//所有的日志按照错误等级分文件存储
	co_log.SetLogger(logs.AdapterMultiFile,`{"filename":"logs/controllers/steam.log","separate":
["emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"]}`)
}


type SteamController struct {
	beego.Controller
}




type BodyMessage struct {
	Message string `json:"message"`
	Status int  `json:"status"`
}


// @Title GetAll
// @Description get all Steam data
// @Success 200 {object} models.SteamInfos
// @router / [get]
func (this *SteamController) GetAll()  {

	//var message BodyMessage
	//token:=this.Ctx.Input.Header("Authorization")
	//if token==""{
	//	message.Status=1
	//	message.Message="token不能为空"
	//	this.Data["json"]=message
	//	this.ServeJSON()
	//	return
	//}
	//token_list:=strings.Split(token," ")
	//if len(token_list)!=2{
	//	message.Status=2
	//	message.Message="token参数错误"
	//	this.Data["json"]=message
	//	this.ServeJSON()
	//	return
	//}
	//if va:=CheckToken(token_list[1]);!va{
	//	message.Status=3
	//	message.Message="token验证不通过"
	//	this.Data["json"]=message
	//	this.ServeJSON()
	//	return
	//}


	var result []map[string]interface{}
	var pagedata models.SteamPages
	one_page_count,err:= beego.AppConfig.Int("steam::entrycount")  //一页数据条数
	if err!=nil{
		co_log.Warning("获取条目配置错误 %s",err)
		one_page_count=10
	}

	page_str:=this.GetString("page","1")  //页数
	page,err:=strconv.Atoi(page_str)
	if err != nil {
		co_log.Warning("页数错误 %s",page_str)
		page=1
	}

	host:=beego.AppConfig.String("steam::mongodbhost")
	database:=beego.AppConfig.String("steam::mongodbdatabase")
	table:=beego.AppConfig.String("steam::mongodbtable")
	database_url:=host+"/"+database
	session,err:=mgo.Dial(database_url)
	if err != nil {
		co_log.Warning("数据库连接错误 %s",err)
	}
	defer session.Close()

	coll_obj:=session.DB(database).C(table)
	err=coll_obj.Find(nil).All(&result)
	if err != nil {
		co_log.Warning("获取记录错误 %s",err)
	}

	pagedata.Count,_=coll_obj.Count()

	page_cout:=pagedata.Count/one_page_count
	if pagedata.Count%one_page_count>0{
		page_cout++
	}

	pagedata.PageCout=page_cout

	if page>=page_cout{
		page=page_cout
	}

	start:=(page-1)*one_page_count
	end:=page*one_page_count
	if end>pagedata.Count{
		end=pagedata.Count
	}

	page_result:=result[start:end]
	if page>1{
		pagedata.Previous=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+this.Ctx.Input.URL()+"?page="+strconv.Itoa(page-1)

	}else {
		pagedata.Previous=nil
	}

	if page<page_cout{
		pagedata.Next=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+this.Ctx.Input.URL()+"?page="+strconv.Itoa(page+1)

	}else {
		pagedata.Next=nil
	}
	pagedata.Current=page
	var new_page_result []interface{}

	for _,row:=range page_result{
		var steam_infos models.SteamInfos
		row["id"]=row["_id"]
		delete(row,"_id")  //删除键值对
		steam_data,_:=json.MarshalIndent(row,"","") //encode json
		err=json.Unmarshal(steam_data,&steam_infos)  //decode json to struct
		if err==nil{
			var classimg []string
			for _,img:=range steam_infos.ClassImg{
				if img!=""{
					//img=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+"/medias/"+img
					img="/medias/"+img
				}
				classimg=append(classimg,img)
			}
			steam_infos.ClassImg=classimg

			var extendedpicture []string
			for _,img:=range steam_infos.ExtendedPicture{
				if img!=""{
					//img=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+"/medias/"+img
					img="/medias/"+img
				}
				extendedpicture=append(extendedpicture,img)
			}
			steam_infos.ExtendedPicture=extendedpicture

			var achievementspicture []string
			for _,img:=range steam_infos.AchievementsPicture{
				if img!=""{
					//img=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+"/medias/"+img
					img="/medias/"+img
				}
				achievementspicture=append(achievementspicture,img)
			}
			steam_infos.AchievementsPicture=achievementspicture


			new_page_result=append(new_page_result,steam_infos)
		}

	}

	pagedata.Results=new_page_result

	this.Data["json"]=pagedata
	this.ServeJSON()
}


// @Title AllData
// @Description get all Steam data
// @Success 200 {object} models.SteamInfos
// @router /alldata [get]
func (this *SteamController) DataAll() {
	one_page_count,err:= beego.AppConfig.Int("steam::entrycount")  //一页数据条数
	if err!=nil{
		co_log.Warning("获取条目配置错误 %s",err)
		one_page_count=10
	}

	page_str:=this.GetString("page","1")  //页数
	page,err:=strconv.Atoi(page_str)
	if err != nil {
		co_log.Warning("页数错误 %s",page_str)
		page=1
	}

	host:=beego.AppConfig.String("steam::mongodbhost")
	database:=beego.AppConfig.String("steam::mongodbdatabase")
	tables:=beego.AppConfig.String("steam::mongodbtable")
	table_list:=strings.Split(tables,";")
	steam_obj:=SteamCollection{
		PageEntrycount:one_page_count,
	}
	init_err:=steam_obj.Init(host,database,table_list...)
	if init_err!=nil{
		this.Ctx.ResponseWriter.Status=500
		return
	}
	pagedata,err:=steam_obj.Get_page_collection(page,this)
	if err!=nil{
		this.Ctx.ResponseWriter.Status=500
		return
	}
	this.Data["json"]=pagedata
	this.ServeJSON()
}
